package com.acme.bankapp.networking.client;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.networking.SocketConnection;
import com.acme.bankapp.service.bank.BankService;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {
    private Bank bank;
    private final String address = "localhost";
    private final int port = 2004;

    void run() {
        try (   SocketConnection sc = new SocketConnection(new Socket(address, port));
                BankClientStub bankClientStub = new BankClientStub(sc)
        ){
            System.out.printf("Connected to %s in port %d\n", address, port);
            chatWithServer(bankClientStub);
        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host! " + unknownHost);
        } catch (ClassNotFoundException|IOException e) {
            e.printStackTrace();
        }
    }

    private void chatWithServer(BankClientStub bankClientStub) throws IOException {
        String message;
        try {
            System.out.println(bankClientStub.onConnect());
            message = bankClientStub.sendReceiveMessageFromConsole();

            if ("report".equals(message)) {
                bank = bankClientStub.getBank();
                System.out.println("client> report received");
                System.out.println(bank);
                BankService.dumpToFile(bank, new File("clientreport.txt"));
            } else {
                System.out.println("server>" + message);
            }
        } catch (ClassNotFoundException classNot) {
            System.err.println("data received in unknown format");
        }
    }

    public static void main(final String args[]) {
        BankClient client = new BankClient();
        client.run();
    }
}
